package utils;

import com.atguigu.lease.common.exception.LeaseException;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    private static   SecretKey  secretKey = Keys.hmacShaKeyFor("zi1ieNjMax7jfiTL9wVg87whX0XxoP2z".getBytes());
    public static String createJwt(Long userid,String username)
    {
        //SecretKey secretKey = Keys.hmacShaKeyFor("zi1ieNjMax7jfiTL9wVg87whX0XxoP2z".getBytes());
        String jwt = Jwts.builder()//构建jwt
                .setExpiration(new Date(System.currentTimeMillis() + 36000000))//设置生成时间,单位是毫秒
                .setSubject("Login_User")//设置主题
                .claim("userId", userid)
                .claim("username", username)
                .signWith(secretKey, SignatureAlgorithm.HS256)//secretkey是key的子类，多态
                .compact();
        //System.out.println("jwt:"+jwt);
        return jwt;
    }

    /*public static Claims parsetoken(String jwt)
    {
        Claims claims = Jwts.parser()//得到解析器
                .setSigningKey(secretKey)//验证jwt  前面两个部分计算得到第三个
                .parseClaimsJws(jwt)
                .getBody();
        return claims;//相当第二部分
    }*/
    public static Claims parseToken(String token){
        System.out.println("Jwt");
        if (token==null){
            throw new LeaseException(305, "未登陆");
        }
        try{
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(secretKey).build();
            return jwtParser.parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e){
            throw new LeaseException(601, "token过期");
        }catch (JwtException e){
            throw new LeaseException(602, "token非法");
        }
    }
    public static void main(String[] args) {
        String cyy = createJwt(2L, "user");
        System.out.println(cyy);
    }
    public static String createAppJwt(String phone)
    {
        //SecretKey secretKey = Keys.hmacShaKeyFor("zi1ieNjMax7jfiTL9wVg87whX0XxoP2z".getBytes());
        String jwt = Jwts.builder()//构建jwt
                .setExpiration(new Date(System.currentTimeMillis() + 36000000))//设置生成时间,单位是毫秒
                .setSubject("Login_Phone")//设置主题
                .claim("Phone", phone)
                .signWith(secretKey, SignatureAlgorithm.HS256)//secretkey是key的子类，多态
                .compact();
        return jwt;
    }
}
